package com.asia5b.a5mall.home.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.home.adapter.CategoryLeftAdapter
import com.asia5b.a5mall.home.adapter.CategoryRightAdapter
import com.asia5b.a5mall.home.databinding.FragmentCategoryBinding
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.logic.viewmodel.home.CategoryFragmentVM
import com.asia5b.a5mall.middleware.model.home.CategoryModel
import com.asia5b.a5mall.middleware.utils.*
import com.scwang.smartrefresh.layout.api.RefreshLayout
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.fragment_category.*

/**
 * Created by zhangyuncai on 2019/12/7.
 */
class CategoryFragment : SimpleFragment<CategoryFragmentVM, FragmentCategoryBinding>() {

    val recyclerViewLeft: RecyclerView
            by lazy {
        rv_category_left
    }
    val recyclerViewRight: RecyclerView by lazy {
        rv_category_right
    }
    val datasLeft = arrayListOf<CategoryModel>()
    private val adapterLeft by lazy {
        CategoryLeftAdapter(datasLeft)
    }
    val datasRight = arrayListOf<CategoryModel>()
    private val adapterRight by lazy { CategoryRightAdapter(this, datasRight) }
    private val emptyView by lazy { newEmptyView(requireContext()) }

    override val viewModelClazz: Class<CategoryFragmentVM>
        get() = CategoryFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentCategoryBinding {
        return FragmentCategoryBinding.inflate(layoutInflater, container, false)
    }


    override fun initView() {
        mSmartRefreshLayout = mDataBinding.autoCategory
        mDataBinding.autoCategory.setEnableLoadMore(false)
        initLeft()
        initRight()
    }

    private fun initLeft() {
        recyclerViewLeft.run {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = adapterLeft
        }
        val linearSnapHelper = LinearSnapHelper()
        linearSnapHelper.attachToRecyclerView(recyclerViewLeft)
        adapterLeft.setOnItemClickListener { adapter, view, position ->
            selectLeftPosition(position)
        }
    }

    private fun selectLeftPosition(position:Int) {
        if (adapterLeft.data.size > position) {
            adapterLeft.selectPosition = position
            adapterLeft.notifyDataSetChanged()
            val categoryModel = adapterLeft.getItem(position) as CategoryModel
            loadRightDatasResult(categoryModel.children ?: arrayListOf())
//            mViewModel.loaRightDatas(categoryModel.parentId)
        }
    }

    private fun initRight() {
        recyclerViewRight.run {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = adapterRight
        }
        UserRepository.getInboxOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    UserRepository.setNums(tv_category_msg_count, it.unread_message_count)
                }.joinComposite(mCompositeDisposable)
    }

    /**
     * @Note   绑定事件
     */
    override fun initEvent() {
        //扫一扫
        iv_category_scan.setOnClickListener {
            push(ActCons.ScanActivity)
        }
        //搜索
        onFilterDoubleClick(ll_category_search_vessel, View.OnClickListener {
            push(ActCons.SearchKeyActivity)
        })

        //消息
        iv_category_msg.setOnClickListener {
            push(ActCons.MessageActivity, isNeedLogin = true)
        }
    }

   override fun startObserver()
    {
        mViewModel.loadLeftDatasLiveData.observe(this, Observer {
            loadLeftDatasResult(it)
        })
    }

    override fun lazyFetchData() {
        loadLeftDatas(0)

    }

    fun loadLeftDatas(refresh: Int) {
        mViewModel.loadLeftDatas(refresh)

    }

    /**
     * 展示子分类
     */
    fun loadRightDatasResult(categoryList: ArrayList<CategoryModel>) {
        if (emptyView.parent == null) {
            adapterRight.setEmptyView(emptyView)
        }
        datasRight.clear()
        datasRight.addAll(categoryList)
        adapterRight.notifyDataSetChanged()

    }

    /**
     * 展示父分类
     */
    fun loadLeftDatasResult(categoryList:ArrayList<CategoryModel>) {
        datasLeft.clear()
        datasLeft.addAll(categoryList)
        ll_category_empty.visibility = (datasLeft.size != 0).judge(View.GONE, View.VISIBLE)
        adapterLeft.selectPosition = 0
        adapterLeft.notifyDataSetChanged()
        if (datasLeft.size > 0) {
            val categoryModel = adapterLeft.getItem(0) as CategoryModel
            loadRightDatasResult(categoryModel.children ?: arrayListOf())
//            presenter.loaRightDatas(categoryList[0].parentId)
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        loadLeftDatas(1)
    }
}